const express = require('express')
const url = require('url')
const router = express.Router()
const pool = require('../pool')

router.get("/", (req, res) => {
  var position = url.parse(req.url, true).query.position
  var username = url.parse(req.url, true).query.username
  var sql = "select * from student where"
  if (position == 0) {
    sql += " teacher = ? order by id desc"
    pool.query(sql, [username], (err, result) => {
      if (err) throw err
      res.send({ code: 1, data: result })
    })
  } else if (position == 1) {

    sql += " manager = ? order by id desc"
    pool.query(sql, [username], (err, result) => {
      if (err) throw err
      res.send({ code: 1, data: result })
    })


  } else {
    var sql = "select * from student order by id desc"
    pool.query(sql, [], (err, result) => {
      if (err) throw err
      res.send({ code: 1, data: result })
    })
  }

})
// 添加学员
router.post('/addstudent', (req, res) => {
  var time = req.body.time
  var name = req.body.name
  var cs = req.body.class
  var phone = req.body.phone
  var product = req.body.product
  var teacher = req.body.teacher
  var manager = req.body.manager
  var admission = req.body.admission
  var status = req.body.status
  var address = req.body.address
  new Promise(open => {
    pool.query("INSERT INTO student VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", ['', time, name, cs, phone, product, teacher, manager, admission, status, address, '', ''], (err, result) => {
      if (err) throw err
      if (result.affectedRows > 0) {
        open()
      } else {
        res.write(JSON.stringify({ ok: 0, msg: "添加失败！" }))
        res.end()
      }
    })
    // })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "添加成功！" }))
    res.end()
  })
})
// 修改学员
router.post('/update', (req, res) => {
  var id = req.body.id
  var time = req.body.time
  var name = req.body.name
  var cs = req.body.class
  var phone = req.body.phone
  var product = req.body.product
  var teacher = req.body.teacher
  var manager = req.body.manager
  var admission = req.body.admission
  var status = req.body.status
  var address = req.body.address
  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true" })
  new Promise(open => {
    pool.query("update student set time=?,name=?,class=?,phone=?,product=?,teacher=?,manager=?,admission=?,status=?,address=? where id=?", [time, name, cs, phone, product, teacher, manager, admission, status, address, id], (err, result) => {
      if (err) throw err
      if (result.affectedRows > 0) {
        open()
      } else {
        res.write(JSON.stringify({ ok: 0, msg: "修改失败！" }))
        res.end()
      }
    })
    // })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "修改成功！" }))
    res.end()
  })
})

// 删除学员
router.post('/delete', (req, res) => {
  var ids = req.body.id
  var names = req.body.name
  var queryParam = names.split(',')

  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*" })
  new Promise(open => {
    pool.query("DELETE FROM student where id in (" + ids + ")", (err, result) => {
      if (err) throw err
      if (result.affectedRows < 0) {
        res.write(JSON.stringify({ ok: 0, msg: "删除失败！" }))
        res.end()
      } else {
        open()
      }
    })
  }).then(() => {
    return new Promise(open => {
      pool.query("SELECT * FROM follow WHERE name IN (?)", [queryParam], (err, result) => {
        if (err) throw err
        if (result.length > 0) {
          pool.query("DELETE  FROM follow WHERE name IN (?)", [queryParam], (err, result) => {
            if (err) throw err
            if (result.affectedRows < 1) {
              res.write(JSON.stringify({ ok: 0, msg: "删除失败！" }))
              res.end()
            } else {
              open()
            }
          })
        } else {
          open()
        }
      })
    })
  }).then(() => {
    return new Promise(open => {
      pool.query("SELECT * FROM tall WHERE name IN (?)", [queryParam], (err, result) => {
        if (err) throw err
        if (result.length > 0) {
          pool.query("DELETE  FROM tall WHERE name IN (?)", [queryParam], (err, result) => {
            if (err) throw err
            if (result.affectedRows < 1) {
              res.write(JSON.stringify({ ok: 0, msg: "删除失败！" }))
              res.end()
            } else {
              open()
            }
          })
        } else {
          open()
        }
      })
    })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "删除成功！" }))
    res.end()
  })
})
// 插入回访学员
router.post('/follow', (req, res) => {
  var name = req.body.name
  var visitor = req.body.visitor
  var content = req.body.content
  var position = req.body.position;
  var cs = req.body.class;
  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*" })
  new Promise(open => {
    pool.query("INSERT INTO follow VALUES(?,curdate(),?,?,?,?)", ['', cs, name, visitor, content], (err, result) => {
      if (err) throw err
      if (result.affectedRows < 0) {
        res.write(JSON.stringify({ ok: 0, msg: "添加回访失败！" }))
        res.end()
      } else {
        open()
      }
    })
  }).then(() => {
    return new Promise(open => {
      var sql = "";
      if (position == 0) {
        sql = "tDate=curdate()"
      } else {
        sql = "mDate=curdate()"
      }
      pool.query("UPDATE student set " + sql + " where name=?", [name], (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
          open()
        } else {
          res.write(JSON.stringify({ ok: 0, msg: "修改回访时间失败！" }))
          res.end()
        }
      })
    })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "添加回访成功！" }))
    res.end()
  })
})
// 查询全部回访学员
router.get('/getFollow', (req, res) => {
  var visitor=req.query.visitor;
  var name=req.query.name;
  var arr=[];
  var sql = "select * from follow"
  if(name && visitor){
    sql+=" where visitor=? and name=?"
    arr=[visitor,name]
  }else if(name){
    sql+=" where name=?"
    arr=[name]
  }else{
    sql+=" where visitor=?"
    arr=[visitor]
  }
  sql+=" order by id desc"
  pool.query(sql, arr,(err, result) => {
    if (err) throw err
    res.send({ code: 1, data: result })
  })
})
// 查询选中日期之间的回访数据
router.get('/getDateFollow', (req, res) => {
  var start = req.query.start
  var end = req.query.end
  var sql = "select * from follow where date between ? and ? order by id desc"
  pool.query(sql, [start, end], (err, result) => {
    if (err) throw err
    res.send({ code: 1, data: result })
  })
})
// 删除学员回访记录
router.post('/deleteFollow', (req, res) => {
  var id = req.body.id
  var name = req.body.name
  var visitor = req.body.visitor
  var position = req.body.position

  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*" })
  new Promise(open => {
    pool.query("DELETE FROM follow where id=?", [id], (err, result) => {
      if (err) throw err
      if (result.affectedRows < 0) {
        res.write(JSON.stringify({ ok: 0, msg: "删除失败！" }))
        res.end()
      } else {
        open()
      }
    })
  }).then(() => {
    return new Promise(open => {
      var date = "(SELECT date FROM `follow` WHERE name=? AND date<= NOW() AND visitor=? order by id DESC limit 1)"
      var sql = "UPDATE student set"
      if (position == 0) {
        sql += " tDate=" + date + " where name=?"
      } else if (position == 1) {
        sql += " mDate=" + date + " where name=?"
      }
      pool.query(sql, [name, visitor, name, name], (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
          open()
        } else {
          res.write(JSON.stringify({ ok: 0, msg: "修改回访时间失败！" }))
          res.end()
        }
      })
    })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "删除成功！" }))
    res.end()
  })
})
// 插入首访表信息
router.post('/insertTall', (req, res) => {
  var name = req.body.name
  var education = req.body.education
  var objective = req.body.objective;
  var specialty = req.body.specialty;
  var JobNature = req.body.JobNature;
  var other = req.body.other;
  var teacher = req.body.teacher;
  var manager = req.body.manager;
  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*" })
  new Promise(open => {
    pool.query("SELECT * FROM tall WHERE name=?", [name], (err, result) => {
      if (err) throw err
      if (result.length > 0) {
        pool.query("UPDATE tall SET education=?,objective=?,specialty=?,JobNature=?,other=? where name=?", [education, objective, specialty, JobNature, other, name], (err, result) => {
          if (err) throw err
          if (result.affectedRows > 0) {
            res.write(JSON.stringify({ ok: 1, msg: "修改首访成功！" }))
            res.end()
          } else {
            open()
          }
        })
      } else {
        open()
      }
    })
  }).then(() => {
    return new Promise(open => {
      pool.query("INSERT INTO tall VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", ['', name, education, objective, specialty, JobNature, other, '', '', '', '', '', '', teacher, manager], (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
          open()
        } else {
          res.write(JSON.stringify({ ok: 0, msg: "添加首访失败！" }))
          res.end()
        }
      })
    })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "添加首访成功！" }))
    res.end()
  })
})
// 查询首访表数据
router.get('/getTall', (req, res) => {
  var name = req.query.name
  if (name) {

    var sql = "select * from tall where name=?"
    pool.query(sql, [name], (err, result) => {
      if (err) throw err
      res.send({ code: 1, data: result })
    })
  } else {
    var sql = "select * from tall"
    pool.query(sql, (err, result) => {
      if (err) throw err
      res.send({ code: 1, data: result })
    })

  }
})
// 插入学员的增值服务
router.post('/updateTall', (req, res) => {
  var name = req.body.name
  var outProduction = req.body.outProduction
  var publicPraise = req.body.publicPraise
  var certificate = req.body.certificate
  var intEducation = req.body.intEducation
  var repPurchase = req.body.repPurchase
  var remark = req.body.remark
  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true" })
  new Promise(open => {
    pool.query(
      "UPDATE tall SET outProduction=?,publicPraise=?,certificate=?,intEducation=?,repPurchase=?,remark=? where name=?",
      [outProduction, publicPraise, certificate, intEducation, repPurchase, remark, name], (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
          open()
        } else {
          res.write(JSON.stringify({ ok: 0, msg: "请添加首访信息！" }))
          res.end()
        }
      })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "添加成功！" }))
    res.end()
  })
})
// 删除学员首访
router.post('/deleteTall', (req, res) => {
  var id = req.body.id

  res.writeHead(200, { "Content-Type": "application/json;charset=utf-8", "Access-Control-Allow-Origin": "*" })
  new Promise(open => {
    pool.query("DELETE FROM tall where id=?", [id], (err, result) => {
      if (err) throw err
      if (result.affectedRows < 0) {
        res.write(JSON.stringify({ ok: 0, msg: "删除失败！" }))
        res.end()
      } else {
        open()
      }
    })
  }).then(() => {
    res.write(JSON.stringify({ ok: 1, msg: "删除成功！" }))
    res.end()
  })
})
module.exports = router;